<template>
  <div class="room-page">
    <div class="page-header">
      <div class="header-left">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索房间..."
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="handleCreate">
          <el-icon><Plus /></el-icon>创建房间
        </el-button>
      </div>
    </div>

    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="roomList"
        style="width: 100%"
        border
      >
        <el-table-column prop="roomName" label="房间名称" min-width="180">
          <template #default="{ row }">
            <div class="room-name-cell">
              <el-image
                :src="row.roomPhoto"
                :preview-src-list="[row.roomPhoto]"
                class="room-photo"
                fit="cover"
              >
                <template #error>
                  <div class="image-placeholder">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
              <span>{{ row.roomName }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="roomInformation" label="房间简介" min-width="200" show-overflow-tooltip />
        
        <el-table-column prop="roomTags" label="标签" min-width="150">
          <template #default="{ row }">
            <div class="tag-group">
              <el-tag
                v-for="tag in row.roomTags?.split(',')"
                :key="tag"
                size="small"
                class="tag-item"
              >
                {{ tag }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="roomStatus" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.roomStatus === 1 ? 'success' : 'info'" size="small">
              {{ row.roomStatus === 1 ? '直播中' : '未开播' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="roomPersons" label="观看人数" width="100" align="center" />
        
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="row.roomStatus === 1"
              type="primary"
              link
              @click="handleEnterRoom(row)"
            >
              进入直播间
            </el-button>
            <template v-else>
              <el-button
                type="primary"
                link
                @click="handleEdit(row)"
              >
                编辑
              </el-button>
              <el-button
                type="danger"
                link
                @click="handleDelete(row)"
              >
                删除
              </el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 房间表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑房间' : '创建房间'"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="roomForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="房间名称" prop="roomName">
          <el-input v-model="roomForm.roomName" placeholder="请输入房间名称" />
        </el-form-item>
        <el-form-item label="房间封面" prop="roomPhoto">
          <el-upload
            class="cover-uploader"
            action="#"
            :show-file-list="false"
            :auto-upload="false"
            :on-change="handleCoverChange"
          >
            <el-image
              v-if="roomForm.roomPhoto"
              :src="roomForm.roomPhoto"
              class="cover-preview"
              fit="cover"
            />
            <div v-else class="upload-placeholder">
              <el-icon><Plus /></el-icon>
              <span>上传封面</span>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="房间简介" prop="roomInformation">
          <el-input
            v-model="roomForm.roomInformation"
            type="textarea"
            rows="3"
            placeholder="请输入房间简介"
          />
        </el-form-item>
        <el-form-item label="房间标签" prop="roomTags">
          <el-select
            v-model="selectedTags"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请选择或输入标签"
            @change="handleTagsChange"
          >
            <el-option
              v-for="tag in tagOptions"
              :key="tag"
              :label="tag"
              :value="tag"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="人数上限" prop="roomPersons">
          <el-input-number
            v-model="roomForm.roomPersons"
            :min="0"
            :max="10000"
            placeholder="请输入人数上限"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Picture } from '@element-plus/icons-vue'
import { List, Create, Update, Delete as DeleteRoom, type LiveSetting } from '@/apis/room'
import type { FormInstance } from 'element-plus'

const router = useRouter()

// 状态变量
const loading = ref(false)
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const roomList = ref<LiveSetting[]>([])
const dialogVisible = ref(false)
const isEdit = ref(false)
const submitLoading = ref(false)
const formRef = ref<FormInstance>()

// 标签选项
const tagOptions = ref(['游戏', '娱乐', '音乐', '知识', '体育'])
const selectedTags = ref<string[]>([])

// 表单数据
const roomForm = ref<LiveSetting>({
  uuid: '',
  roomName: '',
  roomPhoto: '',
  roomInformation: '',
  roomTags: '',
  roomAddress: '',
  roomStatus: 0,
  status: 1,
  roomPersons: 1000,
  roomMessagesGroupsId: 0,
  userUuid: ''
})

// 表单验证规则
const rules = {
  roomName: [
    { required: true, message: '请输入房间名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  roomPhoto: [
    { required: true, message: '请上传房间封面', trigger: 'change' }
  ],
  roomInformation: [
    { required: true, message: '请输入房间简介', trigger: 'blur' },
    { max: 200, message: '长度不能超过 200 个字符', trigger: 'blur' }
  ],
  roomTags: [
    { required: true, message: '请选择房间标签', trigger: 'change' }
  ],
  roomPersons: [
    { required: true, message: '请输入人数上限', trigger: 'blur' },
    { type: 'number', min: 0, message: '人数不能小于0', trigger: 'blur' }
  ]
}

// 获取房间列表
const getRoomList = async () => {
  loading.value = true
  try {
    const { list, total: totalCount } = await List({
      page: currentPage.value,
      pageSize: pageSize.value,
      keyword: searchKeyword.value
    })
    roomList.value = list
    total.value = totalCount
  } catch (error) {
    console.error('获取房间列表失败:', error)
    ElMessage.error('获取房间列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
let searchTimer: NodeJS.Timeout | null = null
const handleSearch = () => {
  if (searchTimer) clearTimeout(searchTimer)
  searchTimer = setTimeout(() => {
    currentPage.value = 1
    getRoomList()
  }, 300)
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  getRoomList()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getRoomList()
}

// 创建房间
const handleCreate = () => {
  isEdit.value = false
  roomForm.value = {
    uuid: '',
    roomName: '',
    roomPhoto: '',
    roomInformation: '',
    roomTags: '',
    roomAddress: '',
    roomStatus: 0,
    status: 1,
    roomPersons: 1000,
    roomMessagesGroupsId: 0,
    userUuid: ''
  }
  selectedTags.value = []
  dialogVisible.value = true
}

// 编辑房间
const handleEdit = (room: LiveSetting) => {
  isEdit.value = true
  roomForm.value = { ...room }
  selectedTags.value = room.roomTags ? room.roomTags.split(',') : []
  dialogVisible.value = true
}

// 删除房间
const handleDelete = (room: LiveSetting) => {
  ElMessageBox.confirm(
    '确定要删除该房间吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await DeleteRoom(room.uuid)
      ElMessage.success('删除成功')
      getRoomList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 进入房间
const handleEnterRoom = (room: LiveSetting) => {
  router.push(`/live?room_uuid=${room.uuid}`)
}

// 处理封面上传
const handleCoverChange = (file: any) => {
  // TODO: 实现文件上传
  roomForm.value.roomPhoto = URL.createObjectURL(file.raw)
}

// 处理标签变化
const handleTagsChange = (tags: string[]) => {
  roomForm.value.roomTags = tags.join(',')
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid, fields) => {
    if (!valid) return
    
    submitLoading.value = true
    try {
      if (isEdit.value) {
        await Update(roomForm.value)
        ElMessage.success('更新成功')
      } else {
        await Create(roomForm.value)
        ElMessage.success('创建成功')
      }
      dialogVisible.value = false
      getRoomList()
    } catch (error) {
      console.error(isEdit.value ? '更新失败:' : '创建失败:', error)
      ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
    } finally {
      submitLoading.value = false
    }
  })
}

// 初始化
onMounted(() => {
  getRoomList()
})
</script>

<style scoped lang="scss">
.room-page {
  padding: 16px;
  height: 100%;
  display: flex;
  flex-direction: column;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    gap: 16px;
    
    .header-left {
      width: 300px;
    }
  }
  
  .table-container {
    flex: 1;
    min-height: 0;
    
    .room-name-cell {
      display: flex;
      align-items: center;
      gap: 8px;
      
      .room-photo {
        width: 60px;
        height: 40px;
        border-radius: 4px;
        
        .image-placeholder {
          width: 100%;
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
          background-color: var(--el-fill-color-light);
          color: var(--el-text-color-secondary);
          font-size: 20px;
        }
      }
    }
    
    .tag-group {
      display: flex;
      flex-wrap: wrap;
      gap: 4px;
      
      .tag-item {
        margin: 0;
      }
    }
  }
  
  .pagination {
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
  }
}

.cover-uploader {
  .cover-preview {
    width: 240px;
    height: 135px;
    border-radius: 4px;
  }
  
  .upload-placeholder {
    width: 240px;
    height: 135px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    border: 1px dashed var(--el-border-color);
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s;
    
    &:hover {
      border-color: var(--el-color-primary);
      
      .el-icon {
        color: var(--el-color-primary);
      }
    }
    
    .el-icon {
      font-size: 24px;
      color: var(--el-text-color-secondary);
      margin-bottom: 8px;
    }
    
    span {
      font-size: 14px;
      color: var(--el-text-color-secondary);
    }
  }
}

// 响应式布局
@media screen and (max-width: 768px) {
  .room-page {
    .page-header {
      flex-direction: column;
      gap: 12px;
      
      .header-left {
        width: 100%;
      }
    }
  }
}
</style>
